/**@type {HTMLCanvasElement} */ 
//上述的注释 是表明下面是canvas节点.vscode会有相关代码提示
const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");
const CANVAS_WIDTH = canvas.width = 600;
const CANVAS_HEIGHT = canvas.height = 600;
//创建要绘制的图片
const img = new Image();
//设置图片路径（这个png中包含所有图片素材）
img.src = "imgs/darkDog.png";
//在这个原图片中 需要的一帧 宽度为575 高度为523
const dogWidth = 575;
const dogHeight = 523;
//定义每一帧播放多少次，实现延迟帧
const frameTime = 10;
//定义当前是第多少帧
let gameFrame = 0
//记录每个动作的名字和总得帧数
let dogAnimate = "run";
const dogState = [
    {
        stataName:"idle",
        frames:7
    },
    {
        stataName:"jump",
        frames:7
    },
    {
        stataName:"fail",
        frames:7
    },
    {
        stataName:"run",
        frames:9
    },
    {
        stataName:"dizzy",
        frames:11
    },
    {
        stataName:"sit",
        frames:5
    },
    {
        stataName:"roll",
        frames:7   
    },
    {
        stataName:"bite",
        frames:7
    },
    {
        stataName:"ko",
        frames:12
    },
    {
        stataName:"getHit",
        frames:4
    },
]
//记录每一帧的帧数名和每一帧的坐标
const frameStats = [];
dogState.forEach((state,index)=>{
    //frames 用于表示 每一个动作的每一帧的坐标信息
    let frames = {
        ioc:[]
    }
    var frameNum = state.frames;
    for(let i = 0;i<frameNum;i++){
        let posx = i * dogWidth;
        let posy = index * dogHeight;
        frames.ioc.push({x:posx,y:posy});
    }
    frameStats[state.stataName] = frames;
})
console.log(frameStats);


/**
 * 该方法用于绘制 动画
 */
function animate(){
    //清空画布的所有区域
    ctx.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
    //记录当前该是横向的第多少个
    let pos = Math.floor(gameFrame/frameTime) % frameStats[dogAnimate].ioc.length; 
    let posx = frameStats[dogAnimate].ioc[pos].x;
    let posy = frameStats[dogAnimate].ioc[pos].y;
    console.log(posx+"----"+posy);
    ctx.drawImage(img,posx,posy,dogWidth,dogHeight,0,0,dogWidth,dogHeight);
    gameFrame++;
    requestAnimationFrame(animate);
    
}

animate();
let choose = document.getElementById("choose");
choose.addEventListener("change",function(e){
    dogAnimate = e.target.value;
})
